package com.ruoyi.mdkt.service.impl;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.mdkt.entity.vo.EventVo;
import com.ruoyi.mdkt.service.EventService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class EventServiceImpl implements EventService {

    public static final String EVENT_PERFIX = "Course_Event_";

    @Autowired
    private RedisCache redisCache;

    @Override
    public Boolean createClassingEvent(Long courseId) {
        String key = EVENT_PERFIX + String.valueOf(courseId);
        Set<EventVo> cacheObject = redisCache.<Set<EventVo>>getCacheObject(key);
        if (cacheObject == null) {
            EventVo eventVo = new EventVo();
            eventVo.setType(1);
            eventVo.setValue("课程已开始");
            Set<EventVo> set = new HashSet<>();
            set.add(eventVo);
            redisCache.setCacheObject(key, set, 6, TimeUnit.HOURS);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public List<EventVo> getEventList(Long courseId) {
        String key = EVENT_PERFIX + String.valueOf(courseId);
        Set<EventVo> set = redisCache.<Set<EventVo>>getCacheObject(key);
        List<EventVo> list = new ArrayList<>();
        for (EventVo e : set) {
            list.add(e);
        }
        return list;
    }

    @Override
    public Boolean addEvent(Long courseId, Integer type, String value, Long id) {
        String key = EVENT_PERFIX + String.valueOf(courseId);
        Set<EventVo> set = redisCache.<Set<EventVo>>getCacheObject(key);
        EventVo eventVo = new EventVo();
        eventVo.setId(id);
        eventVo.setType(type);
        eventVo.setValue(value);
        set.add(eventVo);
        boolean b = redisCache.deleteObject(key);
        if (b) {
            redisCache.setCacheObject(key, set, 4, TimeUnit.HOURS);
            return true;
        } else {
            if (createClassingEvent(courseId)) {
                addEvent(courseId, type, value, id);
                return true;
            } else {
                return false;
            }
        }
    }
}
